<?php

namespace app\api\controller\worker;

use app\Request;
use think\facade\Db;
use think\facade\Env;
use think\response\Json;
use crmeb\exceptions\AdminException;
use think\exception\ValidateException;
use app\api\controller\RestBaseController;
use app\services\worker\RepairWorkerServices;
use app\api\validate\worker\RegisterValidate;
use think\db\exception\{DataNotFoundException, DbException, ModelNotFoundException};

/**
 * 维修师傅注册
 * Class RegisterController
 * @package app\api\controller\worker
 */
class RegisterController extends RestBaseController
{
    /** @var RepairWorkerServices */
    protected $services;

    /**
     * @return void
     */
    protected function initialize()
    {
        parent::initialize();
        $this->services = app()->make(RepairWorkerServices::class);
    }

    /**
     * 维修师傅注册登录
     * @param Request $request
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function registerLogin(Request $request): Json
    {
        $data = $request->postMore([
            ['mobile', ''], // 手机号
            ['code', ''], // 短信验证码
            ['device_type', 'android'],
        ]);

        try {
            validate(RegisterValidate::class)->check($data);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }

        try {
            $res = $this->services->registerLogin($data, $this->allowedDeviceTypes, $request->ip());
        } catch (AdminException $e) {
            $this->error($e->getMessage());
        }

        $this->success("登录成功!", $res);
    }
}
